package com.alks.function.service.impl.administration;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.UserInfoUtil;
import com.alks.common.utils.beanutils.BeanUtil;
import com.alks.common.utils.beanutils.ObjectUtils;
import com.alks.common.utils.excelUtils.ExcelPoiUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.entity.data.entity.PcEmpAttend;
import com.alks.entity.data.entity.PsHoliday2;
import com.alks.entity.data.page.PageRecord;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.data.dto.administration.PcEmpAttendDto;
import com.alks.function.data.dto.administration.PcEmpAttendListDto;
import com.alks.function.data.request.administration.AttendanceDetailsRequest;
import com.alks.function.data.request.administration.PcEmpAttendUpdateRequest;
import com.alks.function.mapper.administration.PcEmpAttendMapper;
import com.alks.function.mapper.administration.PcEmployeeMapper;
import com.alks.function.service.administration.PcEmpAttendService;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PcEmpAttendServiceImpl extends ServiceImpl<PcEmpAttendMapper, PcEmpAttend> implements PcEmpAttendService {

    @Autowired
    private PcEmpAttendMapper pcEmpAttendMapper;

    /**
     * 考勤明细
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo getAttendanceDetails(AttendanceDetailsRequest request) {
        PageRecord<PcEmpAttendDto> list = new PageRecord<>();
        request.setCompanyId(UserInfoUtil.getUserInfo().getCompanyId());
        List<PcEmpAttendDto> all = pcEmpAttendMapper.getAll(request);
        for (PcEmpAttendDto t : all) {
            List<Integer> weekends= getWeekends(t.getYears());
            t.setList(weekends);
        }
        PageInfo pageInfo = new PageInfo(all);
        list.setTotal(pageInfo.getTotal());
        list.setList(all);
        return ResponseInfo.ok(list);
    }

    /**
     * 根据年月拿到周末集合
     * @param years
     */
    private List<Integer>  getWeekends( String years) {
        String[] result = DateUtils.getYearMonth(years);
        int year = Integer.parseInt(result[0]);
        int month = Integer.parseInt(result[1]);
        List<Integer> weekend = DateUtils.getWeekendDays(year, month);
        return weekend;
    }

    /**
     * 员工资料作业查询
     * @param request
     * @return
     */
    @Override
    @AutoPageAop
    public ResponseInfo AttendanceDataQuery(AttendanceDetailsRequest request) {
        PageRecord<PcEmpAttendListDto> list = new PageRecord<>();
        request.setCompanyId(UserInfoUtil.getUserInfo().getCompanyId());
        List<PcEmpAttendListDto> pcEmpAttendList = pcEmpAttendMapper.AttendanceDataQuery(request);
        PageInfo pageInfo=new PageInfo(pcEmpAttendList);
        list.setTotal(pageInfo.getTotal());
        list.setList(pcEmpAttendList);
        return ResponseInfo.ok(list);
    }

    /**
     * 考勤公休日定义
     * @param years
     * @return
     */
    @Override
    public ResponseInfo AttendancePublicHolidays(String years) {
        List<String> psHoliday2 = pcEmpAttendMapper.getPsHoliday2(years);
        return ResponseInfo.ok(psHoliday2);
    }

    @Override
    public ResponseInfo attendancePublicHolidaysV2(String years) {
        return ResponseInfo.ok(pcEmpAttendMapper.getPsHoliday2V2(years));
    }

    /**
     * 考勤修改
     * @param request
     * @return
     */
    @Override
    public ResponseInfo AttendanceDataUpdate(PcEmpAttendUpdateRequest request) {
        if (ObjectUtils.isEmpty(request.getWorkerId())){
            return ResponseInfo.error("工号不能为空");
        }
        if (ObjectUtils.isEmpty(request.getWorkerName())){
            return ResponseInfo.error("姓名不能为空");
        }
        if (ObjectUtils.isEmpty(request.getDdate())){
            return ResponseInfo.error("日期不能为空");
        }
        if (!ObjectUtils.isEmpty(request.getCfmFlag())){
            return ResponseInfo.error("已被财务检核,不能修改!");
        }
        PcEmpAttend pcEmpAttend = new PcEmpAttend();
        BeanUtil.copyProperties(request,pcEmpAttend);
        BigDecimal workHours = getWorkHours(request.getLateMinutes(), request.getEarlyMinutes(), request.getLeaveDays(), request.getOutDays());
        pcEmpAttend.setWorkHours(workHours);
        LambdaUpdateWrapper<PcEmpAttend> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(PcEmpAttend::getWorkerId,request.getWorkerId())
                .eq(PcEmpAttend::getDdate,request.getDdate())
                .eq(PcEmpAttend::getWorkerName,request.getWorkerName())
                .eq(PcEmpAttend::getCompanyId,UserInfoUtil.getUserInfo().getCompanyId());
        pcEmpAttendMapper.update(pcEmpAttend,wrapper);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 根据迟到、早退、请假、请假时数计算正班时数
     * @param lateMinutes 迟到分钟
     * @param earlyMinutes 早退分钟
     * @param leaveDays 请假分钟
     * @param outDays 旷工分钟
     */
    private BigDecimal getWorkHours(BigDecimal lateMinutes, BigDecimal earlyMinutes, BigDecimal leaveDays, BigDecimal outDays) {
        //设置默认工时10
        BigDecimal workHours = BigDecimal.TEN;
        //根据迟到分钟、早退分钟、请假分钟、旷工分钟计算正班时数
        if (ObjectUtils.isEmpty(lateMinutes)){
            lateMinutes=BigDecimal.ZERO;
        }
        if (ObjectUtils.isEmpty(earlyMinutes)){
            earlyMinutes=BigDecimal.ZERO;
        }
        if (ObjectUtils.isEmpty(leaveDays)){
            leaveDays=BigDecimal.ZERO;
        }
        if (ObjectUtils.isEmpty(outDays)){
            outDays=BigDecimal.ZERO;
        }
        // 将分钟转换为小时,保留3位
        BigDecimal lateHours = lateMinutes.divide(BigDecimal.valueOf(60),3,RoundingMode.HALF_UP);
        BigDecimal earlyHours = earlyMinutes.divide(BigDecimal.valueOf(60),3,RoundingMode.HALF_UP);
        BigDecimal leaveHours = leaveDays.divide(BigDecimal.valueOf(60),3,RoundingMode.HALF_UP);
        BigDecimal outHours = outDays.divide(BigDecimal.valueOf(60), 3,RoundingMode.HALF_UP);

        // 计算正班时数保留两位
        workHours = workHours.subtract(lateHours).subtract(earlyHours).subtract(leaveHours).subtract(outHours);
        workHours = workHours.setScale(2, RoundingMode.HALF_UP);
        return workHours;
    }

    /**
     * 考勤删除
     * @param request
     * @return
     */
    @Override
    public ResponseInfo AttendanceDataDel(PcEmpAttendUpdateRequest request) {
        if (ObjectUtils.isEmpty(request.getWorkerId())){
            return ResponseInfo.error("工号不能为空");
        }
        if (ObjectUtils.isEmpty(request.getWorkerName())){
            return ResponseInfo.error("姓名不能为空");
        }
        if (ObjectUtils.isEmpty(request.getDdate())){
            return ResponseInfo.error("日期不能为空");
        }
        if (!ObjectUtils.isEmpty(request.getCfmFlag())){
            return ResponseInfo.error("已被财务检核,不能删除!");
        }
        LambdaUpdateWrapper<PcEmpAttend> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(PcEmpAttend::getWorkerId,request.getWorkerId())
                .eq(PcEmpAttend::getDdate,request.getDdate())
                .eq(PcEmpAttend::getWorkerName,request.getWorkerName())
                .eq(PcEmpAttend::getCompanyId,UserInfoUtil.getUserInfo().getCompanyId());
        pcEmpAttendMapper.delete(wrapper);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 插入当前月周末
     * @param years
     * @return
     */
    @Override
    public ResponseInfo InsertTheWeekendDateOfTheCurrentMonth(String years) {
        if (ObjectUtils.isEmpty(years)){
            return ResponseInfo.error("月份不能为空!");
        }
        String pattern = "\\d{4}\\d{2}";
        boolean check = years.matches(pattern);
        if (!check){
            return ResponseInfo.error("请输入正确的年月格式!");
        }
        String[] result = DateUtils.getYearMonth(years);
        if (result != null) {
            int year = Integer.parseInt(result[0]);
            int month = Integer.parseInt(result[1]);
            List<String> weekend = DateUtils.getWeekendInMonth(year, month);
            if (!ObjectUtils.isEmpty(weekend)){
                //查询数据库是否存在当月数据
                List<String> psHoliday2 = pcEmpAttendMapper.getPsHoliday2(years);
                List<PsHoliday2> list = new ArrayList<>();
                for (String t : weekend) {
                    if (!psHoliday2.contains(t)){
                        PsHoliday2 psHoliday = getPsHoliday2(t);
                        list.add(psHoliday);
                    }
                }
                if (!ObjectUtils.isEmpty(list)){
                    pcEmpAttendMapper.addPsHoliday2(list);
                }
            }
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 对象抽取方法复用
     * @param t
     * @return
     */
    @NotNull
    private PsHoliday2 getPsHoliday2(String t) {
        PsHoliday2 psHoliday = new PsHoliday2();
        UserInfoUtil.UserInfo userInfo = UserInfoUtil.getUserInfo();
        psHoliday.setCompanyId(userInfo.getCompanyId());
        psHoliday.setUserId(userInfo.getLoginName());
        psHoliday.setHolidayDate(LocalDate.parse(t, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        psHoliday.setSysDate(LocalDateTime.now());
        return psHoliday;
    }

    /**
     * 公休日期删除
     * @param years
     * @return
     */
    @Override
    public ResponseInfo psHoliday2Del(String years) {
        if (ObjectUtils.isEmpty(years)){
            return ResponseInfo.error("公休日期不能为空!");
        }
        pcEmpAttendMapper.psHoliday2Del(years);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 公休日期新增
     * @param years
     * @return
     */
    @Override
    public ResponseInfo psHoliday2Add(String years, Integer legalHoliday) {
        if (ObjectUtils.isEmpty(years)){
            return ResponseInfo.error("公休日期不能为空!");
        }
        boolean dateFormat = DateUtils.isValidDateFormat(years);
        if (!dateFormat){
            return ResponseInfo.error("请输入正确的年月格式!");
        }
        String psHoliday2Date = pcEmpAttendMapper.getPsHoliday2Date(years);
        if (!ObjectUtils.isEmpty(psHoliday2Date)){
            return ResponseInfo.error("该公休日期已存在!");
        }
        PsHoliday2 psHoliday = getPsHoliday2(years);
        if (1 == legalHoliday) {
            psHoliday.setLegalHoliday(1);
        } else {
            psHoliday.setLegalHoliday(0);
        }
        pcEmpAttendMapper.psHoliday2Add(psHoliday);
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 公休日期修改
     * @param years
     * @param newYears
     * @return
     */
    @Override
    @Transactional
    public ResponseInfo psHoliday2Update(String years, String newYears, Integer legalHoliday) {
        if (ObjectUtils.isEmpty(years)){
            return ResponseInfo.error("公休日期不能为空!");
        }
        if (ObjectUtils.isEmpty(newYears)){
            return ResponseInfo.error("请输入公休日期!");
        }
        boolean dateFormat = DateUtils.isValidDateFormat(newYears);
        if (!dateFormat){
            return ResponseInfo.error("请输入正确的年月格式!");
        }
        String psHoliday2Date = pcEmpAttendMapper.getPsHoliday2Date(newYears);
        if (!ObjectUtils.isEmpty(psHoliday2Date)){
            return ResponseInfo.error("该公休日期已存在,不能修改!");
        }
        if (1 != legalHoliday) {
            legalHoliday = 0;
        }
        pcEmpAttendMapper.psHoliday2Update(years,newYears,LocalDateTime.now(),UserInfoUtil.getUserInfo().getLoginName(), legalHoliday);
        return ResponseInfo.ok("操作成功!");
    }

    @Resource
    private PcEmployeeMapper pcEmployeeMapper;

    /**
     * 导入考勤资料
     * @param file
     * @return
     */
    @Override
    public ResponseInfo ImportAttendanceData(MultipartFile file) {
        List<PcEmpAttendUpdateRequest> list = excelInput(file);
        if (ObjectUtils.isEmpty(list)){
            throw new ServiceErrorException("请选择正确的文件格式/数据!");
        }

        Map<String, List<PcEmpAttendUpdateRequest>> listMap = list.stream().filter(req -> req.getWorkerId() != null && !req.getWorkerId().isEmpty())
                .collect(Collectors.groupingBy(PcEmpAttendUpdateRequest::getWorkerId));
        boolean flag = listMap.values().stream()
                .anyMatch(data -> data.size() > 1);
        if (flag) {
            log.error("导入文件存在相同工号,导入失败!");
            return ResponseInfo.error("导入文件存在相同工号,导入失败!");
        }
        List<PcEmpAttendUpdateRequest> filteredList = list.stream()
                .filter(t -> !ObjectUtils.isEmpty(t.getWorkerId())&&!t.getWorkerId().equals("日期")&&!t.getWorkerId().equals("工号"))
                .collect(Collectors.toList());

        List<PcEmpAttend> pcEmpAttends = new ArrayList<>();
        LocalDate localDate = null;
        if (!ObjectUtils.isEmpty(filteredList)){
            for (PcEmpAttendUpdateRequest t : filteredList) {
                PcEmpAttend entity = new PcEmpAttend();
                String deptName = pcEmployeeMapper.getEmployeeByWorkerId(t.getWorkerId(), t.getWorkerName());
                if (ObjectUtils.isEmpty(deptName)){
                    log.error("工号:{},姓名:{},不存在,导入失败!",t.getWorkerId(),t.getWorkerName());
                    return ResponseInfo.error("员工:"+t.getWorkerName()+",工号:"+t.getWorkerId()+",不在人事档案中存在,请检查导入文件!");
                }
                BeanUtil.copyProperties(t, entity);
                entity.setDeptName(deptName);
                entity.setCompanyId(UserInfoUtil.getUserInfo().getCompanyId());
                localDate=t.getDdate();
                pcEmpAttends.add(entity);
            }

            List<String> workerIds = pcEmpAttendMapper.getWorkerIds(localDate);
            Set<String> workerIdSet = new HashSet<>(workerIds);
            for (PcEmpAttendUpdateRequest t : filteredList) {
                if (workerIdSet.contains(t.getWorkerId())) {
                    throw new ServiceErrorException("工号:" + t.getWorkerId() + ", 姓名:" + t.getWorkerName() + ", 考勤资料已存在, 不可重复导入!");
                }
            }
        }
        String check = pcEmpAttendMapper.getPcEmpAttend(localDate);
        if (!ObjectUtils.isEmpty(check)){
            throw new ServiceErrorException("该月份考勤已经检核,不能更新处理!");
        }
        if (!ObjectUtils.isEmpty(pcEmpAttends)){
            pcEmpAttendMapper.addPcEmpAttend(pcEmpAttends);
        }
        return ResponseInfo.ok("操作成功!");
    }

    /**
     * 文件导入
     * @param excelFile
     * @return
     */
    public List<PcEmpAttendUpdateRequest> excelInput(MultipartFile excelFile) {
        String excelFileName = excelFile.getOriginalFilename();
        int excelVersion = ExcelPoiUtils.getExcelVersion(excelFileName);
        Workbook workbook = null;
        List<PcEmpAttendUpdateRequest> list = null;

        // 2003版本xls
        if (excelVersion == 1) {
            try {
                log.info("导入文件名:{},文件版本:2003",excelFileName);
                workbook = new HSSFWorkbook(excelFile.getInputStream());
                list = readExcelValue(workbook);
                return list;
            } catch (IOException e) {
                log.error("文件导入失败!");
                e.printStackTrace();
            }
        }
        // 2007版本xlsx
        if (excelVersion == 2) {
            try {
                log.info("导入文件名:{},文件版本:2007",excelFileName);
                workbook = new XSSFWorkbook(excelFile.getInputStream());
                 list = readExcelValue(workbook);
                return list;
            } catch (IOException e) {
                log.error("文件导入失败!");
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 读取Excel
     * @param workbook
     * @return
     */
    private List<PcEmpAttendUpdateRequest> readExcelValue(Workbook workbook) {
        int totalRows = 0;
        int totalCells = 0;
        LocalDate localDate = null;
        // 获取第一张表
        Sheet sheet = workbook.getSheetAt(0);
        // 得到表的总行数
        totalRows = sheet.getPhysicalNumberOfRows();
        // 根据第一行（标题行）获得总列数，获得总列数得根据某行确定
        if (totalRows >= 1 && sheet.getRow(0) != null) {
            totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        List<PcEmpAttendUpdateRequest> list = new ArrayList<>();
        // 逐行取数据，每行对应一条实体对象信息
        for (int rowNum = 1; rowNum < totalRows; rowNum++) {
            // 跳过标题行
            Row row = sheet.getRow(rowNum);
            if (row == null) {
                continue;
            }
            PcEmpAttendUpdateRequest vo = new PcEmpAttendUpdateRequest();
            // 逐列取数据，每列对应一个实体对象属性
            for (int colNum = 0; colNum < totalCells; colNum++) {
                Cell cell = row.getCell(colNum);
                if (null != cell) {
                    switch (cell.getCellType()) {
                        case NUMERIC:
                            if (colNum == 2) {
                                vo.setLateNums(BigDecimal.valueOf(cell.getNumericCellValue()));
                            } else if (colNum == 3) {
                                vo.setLateMinutes(BigDecimal.valueOf(cell.getNumericCellValue()));
                            }
                            if (colNum == 4) {
                                vo.setEarlyNums(BigDecimal.valueOf(cell.getNumericCellValue()));
                            }
                            if (colNum == 5) {
                                vo.setEarlyMinutes(BigDecimal.valueOf(cell.getNumericCellValue()));
                            }
                            if (colNum == 6) {
                                vo.setLeaveDays(BigDecimal.valueOf(cell.getNumericCellValue()));
                            }
                            if (colNum == 7) {
                                vo.setOutDays(BigDecimal.valueOf(cell.getNumericCellValue()));
                            }
                            if (colNum == 8) {
                                vo.setWorkHours(BigDecimal.valueOf(cell.getNumericCellValue()).setScale(2, RoundingMode.HALF_UP));
                            }
                            break;
                        case STRING:
                            if (colNum == 0) {
                                vo.setWorkerId(cell.getStringCellValue());
                            } else if (colNum == 1) {
                                // 定义日期格式正则表达式
                                String dateFormatPattern = "\\d{4}/\\d{1,2}/\\d{1,2}";
                                Pattern pattern = Pattern.compile(dateFormatPattern);
                                Matcher matcher = pattern.matcher(cell.getStringCellValue());
                                if (matcher.matches()) {
                                    Date date = DateUtils.parseDate(cell.getStringCellValue());
                                    Instant instant = date.toInstant();
                                    ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Asia/Shanghai"));
                                    localDate = zonedDateTime.toLocalDate();
                                }
                                vo.setDdate(localDate);
                                vo.setWorkerName(cell.getStringCellValue());
                            }
                            break;
                        case BOOLEAN:
                            break;
                        case FORMULA:
                            if (colNum == 8) {
                                vo.setWorkHours(BigDecimal.valueOf(cell.getNumericCellValue()).setScale(2, RoundingMode.HALF_UP));
                            }
                            break;
                        case BLANK:
                            break;
                        default:
                    }
                }
            }
            list.add(vo);
        }
        if (ObjectUtils.isEmpty(localDate)){
            throw new ServiceErrorException("请检查日期!");
        }
        return list;
    }

    /**
     * 导出考勤报表
     * @param years
     * @param response
     */
    @Override
    public void ExportAttendanceReport(String years, HttpServletResponse response) {
        if (ObjectUtils.isEmpty(years)) {
            throw new ServiceErrorException("请输入年份!");
        }
        AttendanceDetailsRequest request = new AttendanceDetailsRequest();
        request.setYears(years);
        request.setCompanyId(UserInfoUtil.getUserInfo().getCompanyId());
        List<PcEmpAttendDto> all = pcEmpAttendMapper.getAll(request);
        if (ObjectUtils.isEmpty(all)) {
            throw new ServiceErrorException("查询数据为空,不可导出!");
        }
        String fileName = "月考勤表_" + DateUtils.dateTimeNow() + ".xlsx";
        Map<String, Object> mapList = new HashMap<>();
        int seqNo = 1;
        for (PcEmpAttendDto t : all) {
            t.setSeqNo(seqNo++);
        }
        mapList.put("mapList", all);
        mapList.put("years", years);
        try {
            TemplateExportParams templateParams = new TemplateExportParams("templates/考勤导出模板.xls", true);
            ExcelUtils.setResponseZF(response, fileName);
            Workbook workbook = ExcelExportUtil.exportExcel(templateParams, mapList);
            applyWeekendCellStyle(workbook, years);
            workbook.write(response.getOutputStream());
            workbook.close();
        } catch (Exception e) {
            log.error("月考勤表导出失败, 错误信息: {}", e.getMessage(), e);
            throw new ServiceErrorException("月考勤表导出失败!");
        }
    }


    /**
     * 设置标题,周末为颜色
     * @param workbook
     * @param years
     */
    private void applyWeekendCellStyle(Workbook workbook, String years) {
        Sheet sheet = workbook.getSheetAt(0);
        Row titleRow = sheet.getRow(2);
        for (Cell cell : titleRow) {
            String cellValue = cell.getStringCellValue();
            if (cellValue.matches("\\d+")) {
                int day = Integer.parseInt(cellValue);
                List<Integer> weekends= getWeekends(years);
                if (weekends.contains(day)) {
                    CellStyle cellStyle = cell.getCellStyle();
                    CellStyle newCellStyle = workbook.createCellStyle();
                    newCellStyle.cloneStyleFrom(cellStyle);
                    newCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
                    newCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                    cell.setCellStyle(newCellStyle);
                }
            }
        }
    }

    @Override
    public String batchInsert(List<PcEmpAttend> pcEmpAttendList) {
        StringBuffer res = new StringBuffer();
        List<PcEmpAttend> newList = new ArrayList<>();
        LocalDate localDate = null;
        if (!ObjectUtils.isEmpty(pcEmpAttendList)){
            localDate = pcEmpAttendList.get(0).getDdate();
            List<String> workerIds = pcEmpAttendMapper.getWorkerIds(localDate);
            for (PcEmpAttend entity : pcEmpAttendList) {
                String deptName = pcEmployeeMapper.getEmployeeByWorkerId(entity.getWorkerId(), entity.getWorkerName());
                if (ObjectUtils.isEmpty(deptName)){
                    res.append("员工：").append(entity.getWorkerName()).append("【").append(entity.getWorkerId()).append("】不存在,同步失败!\n");
                    log.error("工号:{},姓名:{},不存在,同步失败!",entity.getWorkerId(),entity.getWorkerName());
                    continue;
                }
                entity.setDeptName(deptName);
                entity.setCompanyId(UserInfoUtil.getUserInfo().getCompanyId());
                localDate=entity.getDdate();
                if (workerIds.contains(entity.getWorkerId())) {
                    res.append("员工：").append(entity.getWorkerName()).append("【").append(entity.getWorkerId()).append("】考勤资料已存在,不可重复同步!\n");
                    log.error("工号:"+entity.getWorkerId()+",姓名:"+entity.getWorkerName()+",考勤资料已存在,不可重复同步!");
                    continue;
                }
                newList.add(entity);
            }
        }
        String check = pcEmpAttendMapper.getPcEmpAttend(localDate);
        if (!ObjectUtils.isEmpty(check)){
            res.setLength(0);
            res.append("该月份考勤已经检核,不能更新处理!");
            log.error("该月份考勤已经检核,不能更新处理!");
            return res.toString();
        }
        if (!ObjectUtils.isEmpty(newList)){
            pcEmpAttendMapper.addPcEmpAttend(newList);
        }
        if (res.length() == 0) {
            res.append("考勤资料同步成功!");
        }
        return res.toString();
    }
}
